package org.lee.service

import javax.persistence.EntityManagerFactory

import org.lee.bean.common.CustomBean
import org.lee.bean.domain.ActionLog
import org.lee.bean.domain1.Person1
import org.lee.bean.domain2.Person2
import org.lee.repository1.ActionLog1Repository
import org.lee.repository1.DynaTableRepository
import org.lee.repository1.Person1Repository
import org.lee.repository2.ActionLog2Repository
import org.lee.repository2.Person2Repository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
@Transactional(rollbackFor=Exception.class)
class PersonService {

	@Autowired(required=false) Person1Repository repository1;
	
	@Autowired(required=false) Person2Repository repository2;
	
	@Autowired(required=false) ActionLog1Repository a1repository;
	
	@Autowired(required=false) ActionLog2Repository a2repository;
	
//	@Autowired DynaTableRepository dynaRepository;
	
	@Autowired(required=false) @Qualifier("entityManagerFactory1") EntityManagerFactory factory1;
	
	@Autowired(required=false) @Qualifier("entityManagerFactory2") EntityManagerFactory factory2;
	
	Person1 find1(int id){
		return repository1.findById(id)
	}
	
	Person1 save1(boolean fail){
		Person1 p = repository1.save(new Person1(name:"lee",age:12,updateDate:new Date(), createDate:new Date(), flag:1))
		
		a1repository.save(new ActionLog(action: "add person", createDate: new Date()))
		
		if(fail) 1 / 0
		
		p
	}
	
	List<CustomBean> findCustomBean1(int id){
		factory1.createEntityManager().createNamedQuery("testQuery1").setParameter(1, id).getResultList()
	}
	
	Person2 find2(int id){
		return repository2.findById(id)
	}
	
	Person2 save2(boolean fail){
		Person2 p = repository2.save(new Person2(name:"lee",age:12, updateDate:new Date(), createDate:new Date()))
		
		a2repository.save(new ActionLog(action: "add person", createDate: new Date()))
		
		if(fail) 1 / 0
		
		p
	}
	
	List<CustomBean> findCustomBean2(int id){
		factory2.createEntityManager().createNamedQuery("testQuery2").setParameter(1, id).getResultList()
	}

	def saveBoth(boolean fail){
		Person1 p1 = repository1.save(new Person1(name:"lee",age:12,updateDate:new Date(), createDate:new Date()))
		a1repository.save(new ActionLog(action: "add person", createDate: new Date()))
		
		if(fail) 1 / 0
		
		Person2 p2 = repository2.save(new Person2(name:"lee",age:12, updateDate:new Date(), createDate:new Date()))
		a2repository.save(new ActionLog(action: "add person", createDate: new Date()))
		
		[p1, p2]
	}
	
//	public<T> T saveEntity(T t){
//		dynaRepository.save(t)
//	}
}
